import java.util.regex.Pattern;

public class BinarySearchTree {
    static class TreeNode{
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }
    TreeNode root = null;
    public void insert(int val){
        TreeNode node = new TreeNode(val);
        TreeNode cur = root;
        TreeNode parent = null;
        if(cur == null) {
            root = node;
            return ;
        }
        while(cur != null){
            parent = cur;
            if(cur.val > val){
                cur = cur.left;
            }
            else if(cur.val < val){
                cur = cur.right;
            }
            else {
                return ;
            }
        }
        if(parent.val > val)
            parent.left = node;
        else
            parent.right = node;
    }

    public TreeNode search(int val) {
        TreeNode cur = root;
        while (cur != null) {
            if (cur.val > val)
                cur = cur.left;
            else if (cur.val < val)
                cur = cur.right;
            else
                return cur;
        }
        return null;
    }
    public TreeNode del(int val){
        TreeNode cur = root;
        TreeNode parent = cur;
        while(cur != null){
            if(cur.val < val){
                parent = cur;
                cur = cur.right;
            }
            else if(cur.val > val){
                parent = cur;
                cur = cur.left;
            }
            else{
                delNode(parent, cur);
                return cur;
            }
        }
        return null;
    }
    public void delNode(TreeNode parent, TreeNode cur){
        if(cur.left == null){
            if(cur == parent.left){
                parent.left = cur.right;
            }
            else if(cur == parent.right){
                parent.right = cur.right;
            }
            else{
                root = cur.right;
            }
        }
        else if(cur.right == null){
            if(cur == parent.left){
                parent.left = cur.left;
            }
            else if(cur == parent.right){
                parent.right = cur.left;
            }
            else{
                root = cur.left;
            }
        }
        else{
            TreeNode target = cur.left;
            TreeNode targetP = cur;
            while(target.right != null){
                targetP = target;
                target = target.right;
            }
            cur.val = target.val;
            if(target == target.left){
                cur.left = target.left;
            }
            else{
                targetP.right = target.left;
            }
        }
    }
}
